package com.dy.yunying.biz.controller.datacenter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dy.yunying.api.constant.Constant;
import com.dy.yunying.api.datacenter.export.AdExportDataVo;
import com.dy.yunying.api.dto.XingTuDataDTO;
import com.dy.yunying.api.datacenter.export.XingTuExportDataDTO;
import com.dy.yunying.api.vo.XingTuDataVO;
import com.dy.yunying.biz.service.datacenter.XingTuDataService;
import com.dy.yunying.biz.utils.DateUtils;
import com.dy.yunying.biz.utils.ExportAlibabaUtils;
import com.dy.yunying.biz.utils.ExportUtils;
import com.dy.yunying.biz.utils.MapUtils;
import com.pig4cloud.pig.common.core.exception.BusinessException;
import com.pig4cloud.pig.common.core.util.ECollectionUtil;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.plugin.excel.annotation.ResponseExcel;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 星图统计接口
 */
@RestController
@RequestMapping("/xingtu")
@RequiredArgsConstructor
public class XingTuDataController {

	private static final Map<String, String> XINGTU_GROUP_BY_MAPPING = new HashMap<String, String>() {{
		put("settleType", "settle_type");
		put("authorId", "author_id");
		put("investorId", "investor_id");
		put("appchl", "appchl");
		put("parentchl", "parentchl");
		put("deptId", "dept_id");
		put("pgid", "pgid");
		put("gameid", "gameid");
		put("os", "os");
	}};

	private static final Map<String, String> XINGTU_ORDER_BY_MAPPING = new HashMap<String, String>() {{
		put("cost", "cost");
		put("clickCount", "click_count");
		put("clickRate", "click_rate");
		put("showCount", "show_count");
		put("cpmCost", "cpm_cost");
		put("playCount", "play_count");
		put("orderPrice", "order_price");
		put("finishRate", "finish_rate");
		put("fivesPlayRate", "fives_play_rate");
		put("commentVolume", "comment_volume");
		put("likeVolume", "like_volume");
		put("playVolume", "play_volume");
		put("shareVolume", "share_volume");
		put("deviceCount", "device_count");
		put("clickDeviceRate", "click_device_rate");
		put("registerCount", "register_count");
		put("deviceRegisterRate", "device_register_rate");
		put("deviceCost", "device_cost");
		put("newArpu", "new_arpu");
		put("newPayCount", "new_pay_count");
		put("totalPayCount", "total_pay_count");
		put("newPayRate", "new_pay_rate");
		put("newPayFee", "new_pay_fee");
		put("newPayGivemoney", "new_pay_givemoney");
		put("activePayFee", "active_pay_fee");
		put("activePayGivemoney", "active_pay_givemoney");
		put("weekPayFee", "week_pay_fee");
		put("weekPayGivemoney", "week_pay_givemoney");
		put("monthPayFee", "month_pay_fee");
		put("monthPayGivemoney", "month_pay_givemoney");
		put("activeArpu", "active_arpu");
		put("activeDeviceCount", "active_device_count");
		put("firstDayRoi", "first_day_roi");
		put("firstWeekRoi", "first_week_roi");
		put("firstMonthRoi", "first_month_roi");
		put("totalPayRoi", "total_pay_roi");
		put("totalPayFee", "total_pay_fee");
		put("totalPayGivemoney", "total_pay_givemoney");
		put("retention2", "retention2");
	}};

	private final XingTuDataService xingTuDataService;

	/**
	 * 星图报表总数
	 *
	 * @param xingtu
	 * @return
	 */
	@PostMapping("/count")
	public R<Map<String, Object>> count(@RequestBody XingTuDataVO xingtu) {
		this.requireXingtuQueryBean(xingtu);
		final int page = xingTuDataService.count(xingtu);
		return R.ok(Collections.singletonMap("total", page));
	}

	/**
	 * 星图报表分页
	 *
	 * @param xingtu
	 * @return
	 */
	@PostMapping("/page")
	public R<List<XingTuDataDTO>> page(@RequestBody XingTuDataVO xingtu) {
		this.requireXingtuQueryBean(xingtu);
		final List<XingTuDataDTO> page = xingTuDataService.page(xingtu, true);
		return R.ok(page);
	}

	/**
	 * 星图报表导出
	 *
	 * @param xingtu
	 * @return
	 */
	@GetMapping("/export")
	public void export(@Valid XingTuDataVO xingtu, HttpServletRequest request, HttpServletResponse response) {

		try {
			this.requireXingtuQueryBean(xingtu);
			// 获取列表
			final List<XingTuDataDTO> xingTuList = xingTuDataService.page(xingtu, false);
			xingtu.setCycleType(4).setGroupBys(Collections.emptyList()).setOrderByName(null).setOrderByAsc(null);
			final List<XingTuDataDTO> total = xingTuDataService.page(xingtu, false);
			xingTuList.addAll(total);

			final String sheetName = "短视频数据报表导出";

			String fileName = URLEncoder.encode("短视频数据报表导出-"+ DateUtils.getCurrentTimeNoUnderline(), "UTF-8").replaceAll("\\+", "%20");

			List<Map<String, Object>> resultListMap = MapUtils.objectsToMaps(xingTuList);

			ExportUtils.spliceSuffix(resultListMap, Constant.PERCENT, Constant.DEFAULT_VALUE,"clickRate", "finishRate", "fivesPlayRate", "clickDeviceRate", "deviceRegisterRate", "newPayRate", "firstDayRoi", "firstWeekRoi", "firstMonthRoi", "totalPayRoi", "retention2");


			List<XingTuExportDataDTO> list= new ArrayList<>();

			JSONArray array = JSONArray.parseArray(JSON.toJSONString(resultListMap));

			for (int i = 0; i < array.size(); i++) {
				JSONObject jsonObject = array.getJSONObject(i);
				XingTuExportDataDTO detail = JSON.parseObject(String.valueOf(jsonObject), XingTuExportDataDTO.class);
				list.add(detail);
			}

			ExportAlibabaUtils.exportExcelData(response,sheetName,fileName, xingtu.getExportColumns(),list, XingTuExportDataDTO.class);
		} catch (BusinessException e) {
			throw e;
		} catch (Exception e) {
			throw new BusinessException("导出异常");
		}
	}

	private void requireXingtuQueryBean(XingTuDataVO xingtu) {
		xingtu.setPgids(ECollectionUtil.stringToLongSet(xingtu.getPgidArr()));
		xingtu.setGameids(ECollectionUtil.stringToLongSet(xingtu.getGameidArr()));
		xingtu.setAppchls(ECollectionUtil.stringToStringSet(xingtu.getAppchlArr()));
		xingtu.setDeptIds(ECollectionUtil.stringToLongSet(xingtu.getDeptIdArr()));
		xingtu.setUserGroupIds(ECollectionUtil.stringToLongSet(xingtu.getUserGroupIdArr()));
		xingtu.setInvestorIds(ECollectionUtil.stringToLongSet(xingtu.getInvestorIdArr()));
		xingtu.setGroupBys(Optional.ofNullable(xingtu.getGroupByArr()).filter(StringUtils::isNotEmpty).map(e -> Arrays.asList(e.split(","))).orElse(Collections.emptyList()).stream().map(XINGTU_GROUP_BY_MAPPING::get).filter(StringUtils::isNotEmpty).collect(Collectors.toList()));
		if (StringUtils.isNotEmpty(xingtu.getOrderByName())) {
			xingtu.setOrderByName(XINGTU_ORDER_BY_MAPPING.get(xingtu.getOrderByName()));
		}
	}

	/**
	 * 星图统计报表
	 *
	 * @param xingtu
	 * @return
	 */
	@PostMapping("/page1")
	public R<Page<XingTuDataDTO>> page1(@RequestBody XingTuDataVO xingtu) {
		Page<XingTuDataDTO> page = new Page<>(1, 1, 1, false);
		List<XingTuDataDTO> records = new ArrayList<>();
		page.setRecords(records);
		XingTuDataDTO data = new XingTuDataDTO();
		records.add(data);
		data.setCycleType("汇总");
		data.setSettleType("FIXED_PRICE");
		data.setInvestorId(1L);
		data.setInvestorName("张三");
		data.setAuthorId(11L);
		data.setAuthorName("李四");
		data.setParentchl("toutiao");
		data.setParentchlName("今日头条");
		data.setAppchl("toutiaox111x111x1");
		data.setAppchlName("toutiaox111x111x1");
		data.setDeptId(1L);
		data.setDeptName("运营部");
		data.setPgid(1L);
		data.setPgname("末日血战");
		data.setGameid(1L);
		data.setGname("末日血战Android");
		data.setOs(2);
		data.setAdvertiserId("1111111111111111111");
		data.setDemandId(1L);
		data.setDemandName("任务001");
		data.setTitle("作品001");
		data.setItemId(1L);
		data.setHeadImageUri("http://xxx.xxxx.xxx/xxx.png");
		data.setVideoUrl("http://xxx.xxxx.xxx/xxx.mp4");
		data.setCost(new BigDecimal("11.11"));
		data.setClickCount(111);
		data.setClickRate(new BigDecimal("11.1"));
		data.setShowCount(111);
		data.setCpmCost(new BigDecimal("11.1"));
		data.setPlayCount(111);
		data.setOrderPrice(new BigDecimal("11.1"));
		data.setOnlineTime("2021-12-16 13:46:33");
		data.setFinishRate(new BigDecimal("11.1"));
		data.setFivesPlayRate(new BigDecimal("11.1"));
		data.setCommentVolume(111);
		data.setLikeVolume(111);
		data.setPlayVolume(111);
		data.setShareVolume(111);
		data.setDeviceCount(111);
		data.setClickDeviceRate(new BigDecimal("11.1"));
		data.setRegisterCount(111);
		data.setDeviceRegisterRate(new BigDecimal("11.1"));
		data.setDeviceCost(new BigDecimal("11.1"));
		data.setNewArpu(new BigDecimal("11.1"));
		data.setNewPayCount(111);
		data.setTotalPayCount(111);
		data.setNewPayRate(new BigDecimal("11.1"));
		data.setNewPayFee(new BigDecimal("11.1"));
		data.setActivePayFee(new BigDecimal("11.1"));
		data.setWeekPayFee(new BigDecimal("11.1"));
		data.setMonthPayFee(new BigDecimal("11.1"));
		data.setActiveArpu(new BigDecimal("11.1"));
		data.setActiveDeviceCount(111);
		data.setFirstDayRoi(new BigDecimal("11.1"));
		data.setFirstWeekRoi(new BigDecimal("11.1"));
		data.setFirstMonthRoi(new BigDecimal("11.1"));
		data.setTotalPayRoi(new BigDecimal("11.1"));
		data.setTotalPayFee(new BigDecimal("11.1"));
		data.setRetention2(new BigDecimal("11.1"));
		return R.ok(page);
	}

}
